/**
 * Copyright (C) 2007 Cristian Olaru <colaru@gmail.com>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *         http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.integrationpath.mengine.webapp.action;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.multitype.GenericManageableCaptchaService;
import com.opensymphony.xwork2.Preparable;
import com.integrationpath.mengine.service.GenericManager;
import com.integrationpath.mengine.service.UtilityManager;
import com.integrationpath.mengine.util.OSCacheAdmin;
import com.integrationpath.mengine.model.AppUser;
import com.integrationpath.mengine.model.Article;
import com.integrationpath.mengine.model.Comment;
import com.integrationpath.mengine.webapp.action.BaseAction;
import com.integrationpath.mengine.webapp.listener.StartupListener;
import com.integrationpath.mengine.webapp.util.EngineConstants;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class CommentAction extends BaseAction implements Preparable {
	OSCacheAdmin cacheAdmin = new OSCacheAdmin();
    private GenericManager<Comment, Long> commentManager;
    private GenericManager<Article, Long> articleManager;
	private GenericManager<AppUser, Long> appUserManager;
    private UtilityManager utilityManager;
    private List comments;
    private Comment comment;
    private Long  id;
    private String applicationTheme;
    
    public String getApplicationTheme() {
		return applicationTheme;
	}

	public void setApplicationTheme(String applicationTheme) {
		this.applicationTheme = applicationTheme;
	}

	public GenericManager<AppUser, Long> getAppUserManager() {
		return appUserManager;
	}

	public void setAppUserManager(GenericManager<AppUser, Long> appUserManager) {
		this.appUserManager = appUserManager;
	}

	public GenericManager<Article, Long> getArticleManager() {
		return articleManager;
	}

	public void setArticleManager(GenericManager<Article, Long> articleManager) {
		this.articleManager = articleManager;
	}

	public UtilityManager getUtilityManager() {
		return utilityManager;
	}

	public void setUtilityManager(UtilityManager utilityManager) {
		this.utilityManager = utilityManager;
	}

	public GenericManager<Comment, Long> getCommentManager() {
		return commentManager;
	}

	public void setCommentManager(GenericManager<Comment, Long> commentManager) {
        this.commentManager = commentManager;
    }

    public List getComments() {
        return comments;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
    	setApplicationTheme((String)StartupListener.getAppContext().getAttribute("application_theme"));
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String commentId = getRequest().getParameter("comment.id");
            if (commentId != null && !commentId.equals("")) {
                comment = commentManager.get(new Long(commentId));
            }
        }
    }

    public String list() {
        comments = commentManager.getAll();
        return SUCCESS;
    }

    public void setId(Long  id) {
        this. id =  id;
    }

    public Comment getComment() {
        return comment;
    }

    public void setComment(Comment comment) {
        this.comment = comment;
    }

    public String delete() {
        commentManager.remove(comment.getId());
        saveMessage(getText("comment.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            comment = commentManager.get(id);
        } else {
            comment = new Comment();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }
        
        // remove article page from cache
        // Article article = articleManager.get(comment.getArticle().getId());
        OSCacheAdmin.flushCache(getRequest());
        // OSCacheAdmin.flushCachePattern(getRequest(), "_" + comment.getArticle().getId() + ".html");
        // OSCacheAdmin.flushCachePattern(getRequest(), "getArticleContent.html");
        
        boolean isNew = (comment.getId() == null);
        
        comment.setStatus(EngineConstants.COMMENT_STATUS_ENABLED);

        comment.setDate(new Date());
        commentManager.save(comment);
        
        AppUser adminUser = appUserManager.get(1L);    
		utilityManager.sendMailToUser(getText("comment.form.email.subject", new String[] {comment.getNickname(), comment.getTitle()}), getText("comment.form.email.body", new String[] {comment.getNickname(), comment.getContent()}), adminUser, getRequest(), "office@javaromania.com");
		
        String key = (isNew) ? "comment.added" : "comment.updated";
        
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
        
        
    }
    
    @Override
    public void validate() {
    	super.validate();
    	
    	// validating robots
		 if (getRequest().getMethod().equalsIgnoreCase("post")) {
			 // getFieldErrors().clear();
			 Boolean isResponseCorrect =Boolean.FALSE;
			 // remember that we need an id to validate!
			 String captchaId = getSession().getId();
			 //retrieve the response
			 String response = getRequest().getParameter("j_captcha_response");
			 // Call the Service method
			 try {
			       GenericManageableCaptchaService imageCaptchaService = (GenericManageableCaptchaService)getSpringContext(getRequest()).getBean("imageCaptchaService");

				 isResponseCorrect = imageCaptchaService.validateResponseForID(captchaId,
				 response);
			 } catch (CaptchaServiceException e) {
				 //should not happen, may be thrown if the id is not valid
			 }
		 
			 if(!isResponseCorrect)
			 addActionError(getText("errors.captcha.string"));
			 //do something according to the result!
		 }
		 
		 
		 getRequest().getSession().setAttribute("fieldErrors", getFieldErrors() );
		 getRequest().getSession().setAttribute("actionErrors", getActionErrors() );
		 getRequest().getSession().setAttribute("comment", comment );
    }
    
    private WebApplicationContext getSpringContext(HttpServletRequest request) {
    	return WebApplicationContextUtils.getWebApplicationContext(
    			request.getSession().getServletContext());
        }
}